package com.szit.test.dao.impl;

import com.szit.test.dao.MySqlConnection;
import com.szit.test.dao.CategoryDao;
import com.szit.test.entity.Category;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 籍贯数据访问层实现类
 *
 * @author 勇哥
 * @version 1.0 2025-05-20
 */
public class CategoryDaoImpl implements CategoryDao {
    private MySqlConnection db;

    public CategoryDaoImpl(){
        db = new MySqlConnection();
    }

    @Override
    public Category getProvinceById(int id) {
        Category p = null;

        // 1.定义SQL语句：添加一条记录
        String sql = "SELECT * FROM category WHERE id=?";

        // 2.定义参数集合
        Object[]parameters = {id};

        // 3.调用通用连接类
        ResultSet rs = db.getResultSet(sql, parameters);

        try {
            // 4. 将结果集数据倒存入到集合中
            if (rs.next()) {
                // 将每条记录存到实体对象中
                p = new Category();
                p.setId(rs.getInt("id"));
                p.setName(rs.getString("name"));
            }
            // 关闭对象
            db.close();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return p;
    }

    @Override
    public List<Category> getAllProvinces() {
        List<Category> lists = new ArrayList<Category>();

        // 1.定义SQL语句：添加一条记录
        String sql = "SELECT * FROM category";

        // 3.调用通用连接类
        ResultSet rs = db.getResultSet(sql, null);

        try {
            // 4. 将结果集数据倒存入到集合中
            while (rs.next()) {
                // 将每条记录存到实体对象中
                Category p = new Category();
                p.setId(rs.getInt("id"));
                p.setName(rs.getString("name"));

                lists.add(p);
            }
            // 关闭对象
            db.close();
        }catch (SQLException e){
            e.printStackTrace();
        }

        return lists;
    }
}
